define([ 'angular','attachments'], function(angular) {
'use strict';
	angular.module('inventory.itemBatchSingle', ['app.attachments'])

	.controller('itemBatchSingleCtrl'
			,['$rootScope', '$scope','systemService', 'BizData'
			  , '$uibModalInstance','params', 'title', f])//控制器结束
	function f($rootScope, $scope, systemService, BizData
					   , $uibModalInstance, params, title) {


		var Model = this;
		
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码
		var billType = 'PHDA';
		var billTypeName = "批号档案";
		var flowType = 0;
		var autoCode; //是否自动编码
		var revOpay; //入库出库
		var direction;
		var costingCode; //影响成本码
		var origin;
		var originName = "";
		var billNo = "";
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
		
		Model.dataMasterAfterRefresh = function(event) {
			//打开窗口之后，至于编辑状态
			Model.edit();
		}
		

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}



		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			//计算有效期至
			/*
			if(event.column=='produceDate'){
				var dataDetail = event.source;
				var rowID = dataDetail.getID(event.rowIndex);
				var produceDate = dataDetail.getValue('produceDate',rowID);
//				var d = justep.Date.fromString(produceDate,justep.Date.STANDART_FORMAT_SHOT);//'yyyy-MM-dd'//justep.Date.STANDART_FORMAT_SHOT
				var d = produceDate;//'yyyy-MM-dd'
				//alert('生产日期-->'+produceDate+'-->'+d.toString());
				//获取有效天数
				var validDays = parseInt(dataDetail.getValue('validDays',rowID));
		//		alert('有效天数-->'+validDays);
//				var validDate = justep.Date.increase(d,validDays,'d');
				var validDate = common.getNewDay(d,validDays);
				dataDetail.setValue('validDate',validDate,rowID);
				//获取复检天数
				var checkoutAgainDays = parseInt(dataDetail.getValue('checkoutAgainDays',rowID));
//				var checkoutAgainDate = justep.Date.decrease(validDate,checkoutAgainDays,'d');
				var checkoutAgainDate = common.getNewDay(validDate,-checkoutAgainDays);
//				dataDetail.setValue('checkoutAgainDate',justep.Date.toString(checkoutAgainDate,justep.Date.STANDART_FORMAT_SHOT),rowID);
				dataDetail.setValue('checkoutAgainDate',checkoutAgainDate,rowID);
			}
			*/

		}
		


		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {

		};
		
		
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){

			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			event.source.setValue('billType',billType,event.id);
			event.source.setValue('billTypeName',billTypeName,event.id);
		}


		Model.gridRowClick = function(event){
			
			
		}

		Model.gridRowDblClick = function(event){
			Model.edit();
		}
		
		
		Model.dataMasterBeforeSave = function(event) {
//			console.log('dataMasterBeforeSave-->',event);
		};
		
		Model.dataMasterAfterSave = function(event) {
//			console.log('dataMasterAfterSave-->',event);
			//保存成功
			$uibModalInstance.close(0);  
		};
		

		//打开对话框（选择物料）
		Model.triggerItemNoClick = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			options.batchNo = 'Y';
			
			var modalInstance = systemService.openItemNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var simpleRow = event.data[0];
//	        	systemService.itemSelectSingle(simpleRow,$scope.dataDetail);
         		var dataDetail = Model.dataMaster;
         		var rowID = dataDetail.getCurrentID();

     			dataDetail.setValue('itemID', simpleRow.fID, rowID);
				dataDetail.setValue('itemNo', simpleRow.itemNo, rowID);
				dataDetail.setValue('itemName', simpleRow.itemName, rowID);
				dataDetail.setValue('itemProperty', simpleRow.itemProperty, rowID);
				dataDetail.setValue('itemDescribe', simpleRow.itemDescribe, rowID);
//				dataDetail.setValue('unitCode', simpleRow.unitCode, rowID);
				dataDetail.setValue('unitName', simpleRow.unitName, rowID);
				dataDetail.setValue('qualityType',simpleRow.qualityType,rowID);
				dataDetail.setValue('qualityTypeLabel',simpleRow.qualityTypeLabel,rowID);
				dataDetail.setValue('qualityPeriod',simpleRow.qualityPeriod,rowID);
				dataDetail.setValue('validDays',simpleRow.validDays,rowID);
				dataDetail.setValue('checkoutAgainDays',simpleRow.checkoutAgainDays,rowID);
				dataDetail.setValue('process',simpleRow.process,rowID);
				dataDetail.setValue('processLabel',simpleRow.processLabel,rowID);
				dataDetail.setValue('storeNo',simpleRow.storeNo,rowID);
				dataDetail.setValue('images', simpleRow.images, rowID);

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		
		var options = {};
		options.container = Model;
		options.concept = 'ItemBatch';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/inventory/itemBatch/list/create';
		options.reader = '/inventory/itemBatch/list/query';
		options.writer = '/inventory/itemBatch/list/save';
		options.deleter = '/inventory/itemBatch/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.defCols = {fID:{name:"fID",type:"String",label:""},systemCode:{name:"systemCode",type:"String",label:""},billType:{name:"billType",type:"String",label:""},billTypeName:{name:"billTypeName",type:"String",label:""},orderDate:{name:"orderDate",type:"Date",label:""},state:{name:"state",type:"String",label:""},status:{name:"status",type:"String",label:""},itemID:{name:"itemID",type:"String",label:""},itemNo:{name:"itemNo",type:"String",label:""},itemName:{name:"itemName",type:"String",label:""},itemProperty:{name:"itemProperty",type:"String",label:""},itemDescribe:{name:"itemDescribe",type:"String",label:""},unitCode:{name:"unitCode",type:"String",label:""},unitName:{name:"unitName",type:"String",label:""},batchNo:{name:"batchNo",type:"String",label:""},batchDescribe:{name:"batchDescribe",type:"String",label:""},qualityPeriod:{name:"qualityPeriod",type:"Integer",label:""},validDays:{name:"validDays",type:"Integer",label:""},checkoutAgainDays:{name:"checkoutAgainDays",type:"Integer",label:""},qualityType:{name:"qualityType",type:"Integer",label:""},qualityTypeLabel:{name:"qualityTypeLabel",type:"String",label:""},process:{name:"process",type:"String",label:""},processLabel:{name:"processLabel",type:"String",label:""},storeNo:{name:"storeNo",type:"String",label:""},produceDate:{name:"produceDate",type:"Date",label:""},validDate:{name:"validDate",type:"Date",label:""},checkoutAgainDate:{name:"checkoutAgainDate",type:"Date",label:""},firstStoreDate:{name:"firstStoreDate",type:"Date",label:""},lastCheckDate:{name:"lastCheckDate",type:"Date",label:""},brand:{name:"brand",type:"String",label:""},brandLabel:{name:"brandLabel",type:"String",label:""},placeOrigin:{name:"placeOrigin",type:"String",label:""},manufacturer:{name:"manufacturer",type:"String",label:""},providerID:{name:"providerID",type:"String",label:""},storageTypeD:{name:"storageTypeD",type:"String",label:""},storageTypeDLabel:{name:"storageTypeDLabel",type:"String",label:""},providerNo:{name:"providerNo",type:"String",label:""},shortName:{name:"shortName",type:"String",label:""},providerName:{name:"providerName",type:"String",label:""},origin:{name:"origin",type:"String",label:""},originName:{name:"originName",type:"String",label:""},originNo:{name:"originNo",type:"String",label:""},originSerialNo:{name:"originSerialNo",type:"String",label:""},quantityL:{name:"quantityL",type:"Decimal",label:""},pieceQuantityL:{name:"pieceQuantityL",type:"Decimal",label:""},lockFlag:{name:"lockFlag",type:"String",label:""},comments:{name:"comments",type:"String",label:""},cUsercode:{name:"cUsercode",type:"String",label:""},cUsername:{name:"cUsername",type:"String",label:""},cDatetime:{name:"cDatetime",type:"Datetime",label:""},tUsercode:{name:"tUsercode",type:"String",label:""},tUsername:{name:"tUsername",type:"String",label:""},tDatetime:{name:"tDatetime",type:"Datetime",label:""},eUsercode:{name:"eUsercode",type:"String",label:""},eUsername:{name:"eUsername",type:"String",label:""},eDatetime:{name:"eDatetime",type:"Datetime",label:""},userId:{name:"userId",type:"String",label:""},enterpriseNo:{name:"enterpriseNo",type:"String",label:""},enterpriseName:{name:"enterpriseName",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = 15;
		options.orderBy = 'batchNo ASC'
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onAfterRefresh = Model.dataMasterAfterRefresh;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);

		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////
		//接收调用的参数
//		Model.params = $rootScope.$stateParams;  

		//刷新数据
//	    Model.dataMaster.refreshData();

		////////////////////启动执行结束///////////////////////////////////////////////////
		
		//新建
		Model.add = function(){
		    var options = {
		    		index : 0,
		    		defaultValues : [
		    			{
			            	 state:'active'
			            	 ,status:'open'
			            	 ,audit:'active'
			            	 
			            	 ,itemQuantityL:0
			            	 ,pieceQuantityL:0
			            	 
			            	 ,qualityPeriod:0
			     						            	 
			            	 ,billType: billType
			            	 ,orderDate: ':getCurrentDate()'
				             ,employeeNo: ':getCurrentPsmFID()'
					         ,employeeName: ':getCurrentPsmFName()'
				             ,cUsercode: ':getCurrentPersonCode()'
					         ,cUsername: ':getCurrentPersonName()'
						     ,cDatetime: ':getCurrentDateTime()'
							 ,userId: ':getCurrentPersonID()'
							 ,enterpriseNo: ':getCurrentOgnFID()'
							 ,enterpriseName: ':getCurrentOgnLongName()'
							 ,version: 0

			            }
			            //,{itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataMaster.newData(options);
		};
		
		//修改
		Model.edit = function(){
			Model.dataMaster.userdata.recordState = 'edit';
		}
		 
        Model.ok = function () {  
	    	Model.dataMaster.saveData();
	    };  
	    
	    Model.cancel = function () {  
	        $uibModalInstance.dismiss('cancel');  
	    };    
		
		
		
		//////////////////////对话框使用开始//////////////////////////////////////
        //模态窗口打开之后执行的事件
        $uibModalInstance.opened.then(function(){
    		//接收调用对话框的参数
            Model.title = title;  
            Model.params = params;  
    		 
    		if(Model.params.recordState=='new'){
    			Model.add();
    		}
    		
    		if(Model.params.recordState=='edit'){
//    			Model.dataMaster.filter = "fID='"+params.id+"'";
    			Model.dataMaster.id = Model.params.id;
    		    Model.dataMaster.refreshData();
    		}
        });  
		//////////////////////对话框使用结束//////////////////////////////////////

	
	    return Model;

	}	
	
});
	
